package com.hz.airline.task.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hz.airline.bean.OrderAccount;
import com.hz.airline.bean.RefoundOrder;
import com.hz.airline.bean.RegStatusBean;
import com.hz.airline.dao.*;
import com.hz.airline.entity.*;
import com.hz.airline.task.BaseServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.hz.airline.util.Constants.Logger;


/**
 * Created by kevin on 2020/2/1 16:30
 */
@RestController
public class ServletManger extends BaseServlet {

    @Autowired
    private UserAccountDao userAccountDao;

    @Autowired
    private RegStatusDao regStatusDao;

    @Autowired
    private PassengerDao passengerDao;

    @Autowired
    private LinkManDao linkManDao;

    @Autowired
    private SystemTipDao systemTipDao;

    @Autowired
    private FlightDao flightDao;

    @Autowired
    private FlightPlayDao flightPlayDao;

    @Autowired
    private UserOrderDao userOrderDao;

    @Autowired
    private FlightInfomationDao flightInfomationDao;

    @Autowired
    private SpecialTicketDao specialTicketDao;

    @Autowired
    private UserTripSummaryDao userTripSummaryDao;

    @Autowired
    private UserOrderSeatsDao userOrderSeatsDao;

    @Autowired
    private PersonExpenseDao personExpenseDao;

    @Autowired
    private CompanyExpenseDao companyExpenseDao;

    @Autowired
    private UserMemberZoneDao userMemberZoneDao;

    @RequestMapping(value = "/reg/account", method = RequestMethod.POST)
    @ResponseBody
    public String reg_account(@RequestBody String request) {
        Logger.info("[==== reg/account ====] request：" + request);
        // 转数据
        User bean = JSONObject.parseObject(request, User.class);
        // 查询是否注册
        User isUser = userAccountDao.findByMobileAndIdnumberAndUsername(bean.getMobile(), bean.getIdnumber(), bean.getUsername());
        if (isUser != null) {
            return response(1203, "该用户已经注册过", null);
        }
        // 拼接数据
        User user = new User();
        user.setPermissionid(1);
        user.setCreatetime(new Date());
        user.setUpdatetime(new Date());
        user.setEmail(bean.getEmail());
        user.setMobile(bean.getMobile());
        user.setGender(bean.getGender());
        user.setIdnumber(bean.getIdnumber());
        user.setUsername(bean.getUsername());
        user.setPassword(bean.getPassword());
        user.setUserid(UUID.randomUUID().toString());
        // 存账号到数据库
        User saveUser;
        try {
            saveUser = userAccountDao.save(user);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "账号存储失败", null);
        }
        // 存联系人到数据库
        LinkMan linkMan = new LinkMan();
        linkMan.setUserid(saveUser.getUserid());
        linkMan.setUsername(bean.getUsername());
        linkMan.setEmail(bean.getEmail());
        linkMan.setMobile(bean.getMobile());
        linkMan.setCreatetime(new Date());
        linkMan.setUpdatetime(new Date());
        try {
            linkManDao.save(linkMan);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "存联系人存数据失败", null);
        }
        // 存乘机人到数据库
        Passenger passenger = new Passenger();
        passenger.setUserid(saveUser.getUserid());
        passenger.setUsername(bean.getUsername());
        passenger.setEmail(bean.getEmail());
        passenger.setMobile(bean.getMobile());
        passenger.setGender(bean.getGender());
        passenger.setIdnumber(bean.getIdnumber());
        passenger.setCreatetime(new Date());
        passenger.setUpdatetime(new Date());
        try {
            passengerDao.save(passenger);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "存乘机人存数据失败", null);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userid", saveUser.getUserid());
        return response(1200, "成功", jsonObject);
    }

    @RequestMapping(value = "/search/account", method = RequestMethod.POST)
    @ResponseBody
    public String search_account(@RequestBody String request) {
        Logger.info("[==== search/account ====] request：" + request);
        try {
            // 转数据
            User bean = JSONObject.parseObject(request, User.class);
            // 查找用户
            User user = userAccountDao.findByMobileAndPassword(bean.getMobile(), bean.getPassword());
            if (user == null) {
                return response(1202, "请检查账号密码是否正确", null);
            }
            return response(1200, "成功", JSONObject.toJSON(user));
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
        }
        return response(1202, "请检查账号密码是否正确", null);
    }

    @RequestMapping(value = "/search/user", method = RequestMethod.POST)
    @ResponseBody
    public String search_user(@RequestBody String request) {
        Logger.info("[==== search/user ====] request：" + request);
        try {
            // 转数据
            User bean = JSONObject.parseObject(request, User.class);
            // 查找用户
            User user = userAccountDao.findByUserid(bean.getUserid());
            if (user == null) {
                return response(1202, "请检查用户编号是否正确", null);
            }
            user.setServeredate(new Date());
            String response = response(1200, "成功", JSONObject.toJSON(user));
            // 更想时间
            user.setUpdatetime(new Date());
            userAccountDao.save(user);
            return response;
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
        }
        return response(1202, "请检查用户编号是否正确.", null);
    }

    @RequestMapping(value = "/modify/user/infomation", method = RequestMethod.POST)
    @ResponseBody
    public String modify_user_infomation(@RequestBody String request) {
        Logger.info("[==== modify/user/infomation ====] request：" + request);
        // 转数据
        User bean = JSONObject.parseObject(request, User.class);
        try {
            // 查找用户
            User user = userAccountDao.findByUserid(bean.getUserid());
            if (user == null) {
                return response(1202, "请检查用户编号是否正确", null);
            }
            // 更新用户名
            if (bean.getUsername() != null) {
                // 更新行程
                UserTripSummary tripSummary = userTripSummaryDao.findByUsernameAndIdnumberAndUserid(user.getUsername(), user.getIdnumber(), user.getUserid());
                tripSummary.setUsername(bean.getUsername());
                userTripSummaryDao.save(tripSummary);
                // 更新用户表
                user.setUsername(bean.getUsername());
            }
            // 更新性别
            else if (bean.getGender() != null) {
                user.setGender(bean.getGender());
            }
            // 更新邮箱
            else if (bean.getEmail() != null) {
                user.setEmail(bean.getEmail());
            }
            // 更新手机号
            else if (bean.getMobile() != null) {
                user.setMobile(bean.getMobile());
            }
            // 更新身份证号
            else if (bean.getIdnumber() != null) {
                // 更新行程
                UserTripSummary tripSummary = userTripSummaryDao.findByUsernameAndIdnumberAndUserid(user.getUsername(), user.getIdnumber(), user.getUserid());
                tripSummary.setIdnumber(bean.getIdnumber());
                userTripSummaryDao.save(tripSummary);
                // 更新用户表
                user.setIdnumber(bean.getIdnumber());
            }
            userAccountDao.save(user);
            // 响应报文
            user.setServeredate(new Date());
            return response(1200, "成功", JSONObject.toJSON(user));
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
        }
        return response(1201, "修改数据失败", null);
    }

    @RequestMapping(value = "/modify/user", method = RequestMethod.POST)
    @ResponseBody
    public String modify_user(@RequestBody String request) {
        Logger.info("[==== modify/user ====] request：" + request);
        // 转数据
        User bean = JSONObject.parseObject(request, User.class);
        try {
            // 查找用户
            User user = userAccountDao.findByUserid(bean.getUserid());
            if (user == null) {
                return response(1202, "请检查用户编号是否正确", null);
            }
            // 会员过期
            if (bean.getOpenmoney() == null || bean.getOpenmoney().length() == 0) {
                user.setPermissionid(3);
                user.setExpiredate(null);
                userAccountDao.save(user);
                return response(1200, "成功", JSONObject.toJSON(user));
            }
            // 会员开通
            user.setPermissionid(2);
            user.setOpenmoney(bean.getOpenmoney());
            switch (bean.getOpenmoney()) {
                case "199":
                    user.setExpiredate(getExpireDate(30));
                    break;
                case "499":
                    user.setExpiredate(getExpireDate(90));
                    break;
                case "999":
                    user.setExpiredate(getExpireDate(365));
                    break;
                default:
                    user.setPermissionid(1);
                    user.setOpenmoney(null);
                    user.setExpiredate(null);
            }
            userAccountDao.save(user);
            return response(1200, "成功", JSONObject.toJSON(user));
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
        }
        return response(1201, "修改数据失败", null);
    }

    @RequestMapping(value = "/person/infomation", method = RequestMethod.POST)
    @ResponseBody
    public String person_infomation(@RequestBody String request) {
        Logger.info("[==== person/infomation ====] request：" + request);
        // 转数据
        User bean = JSONObject.parseObject(request, User.class);
        // 查找用户
        User user = userAccountDao.findByMobileAndUsernameAndIdnumber(bean.getMobile(), bean.getUsername(), bean.getIdnumber());
        if (user == null) {
            return response(1202, "该用户没有注册过", null);
        }
        user.setServeredate(new Date());
        return response(1200, "成功", JSONObject.toJSON(user));
    }

    @RequestMapping(value = "/reg/status", method = RequestMethod.POST)
    @ResponseBody
    public String reg_status(@RequestBody String request) {
        Logger.info("[==== reg/status ====] request：" + request);
        // 转数据
        RegStatusBean bean = JSONObject.parseObject(request, RegStatusBean.class);
        // 查找用户
        RegStatus regStatus = regStatusDao.findByUsernameAndDeviceid(bean.getUsername(), bean.getDeviceid());
        // 存到数据库
        if (regStatus == null) {
            regStatus = new RegStatus();
        }
        regStatus.setUsername(bean.getUsername());
        regStatus.setDeviceid(bean.getDeviceid());
        // 区分开通的场景
        switch (bean.getDesc()) {
            case "facelogin":
                regStatus.setFacelogin(bean.getStatus());
                break;
            case "fingerlogin":
                regStatus.setFingerlogin(bean.getStatus());
                break;
            case "gesturelogin":
                regStatus.setGesturelogin(bean.getStatus());
                break;
            case "facepay":
                regStatus.setFacepay(bean.getStatus());
                break;
            case "fingerpay":
                regStatus.setFingerpay(bean.getStatus());
                break;
            case "gesturepay":
                regStatus.setGesturepay(bean.getStatus());
                break;
            default:
                return response(1204, "参数错误", null);
        }
        try {
            regStatusDao.save(regStatus);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "开通存数据失败", null);
        }
        return response(1200, "成功", null);
    }

    @RequestMapping(value = "/search/status", method = RequestMethod.POST)
    @ResponseBody
    public String search_status(@RequestBody String request) {
        Logger.info("[==== search/status ====] request：" + request);
        // 转数据
        RegStatusBean bean = JSONObject.parseObject(request, RegStatusBean.class);
        // 查找用户
        RegStatus regStatus = regStatusDao.findByUsernameAndDeviceid(bean.getUsername(), bean.getDeviceid());
        if (regStatus == null) {
            return response(1205, "未开通任何方式", null);
        }
        // 响应报文
        JSONObject jsonObject = new JSONObject();
        // 登录
        jsonObject.put("facelogin", regStatus.getFacelogin());
        jsonObject.put("fingerlogin", regStatus.getFingerlogin());
        jsonObject.put("gesturelogin", regStatus.getGesturelogin());
        // 支付
        jsonObject.put("facepay", regStatus.getFacepay());
        jsonObject.put("fingerpay", regStatus.getFingerpay());
        jsonObject.put("gesturepay", regStatus.getGesturepay());
        return response(1200, "成功", jsonObject);
    }

    @RequestMapping(value = "/modify/password", method = RequestMethod.POST)
    @ResponseBody
    public String modify_password(@RequestBody String request) {
        Logger.info("[==== modify/password ====] request：" + request);
        // 转数据
        User bean = JSONObject.parseObject(request, User.class);
        // 查找用户
        User user = userAccountDao.findByUserid(bean.getUserid());
        if (user == null) {
            return response(1202, "上送数据不正确", null);
        }
        user.setPassword(bean.getPassword());
        user.setUpdatetime(new Date());
        try {
            userAccountDao.save(user);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "密码存数据失败", null);
        }
        return response(1200, "成功", null);
    }

    @RequestMapping(value = "/foget/password", method = RequestMethod.POST)
    @ResponseBody
    public String foget_password(@RequestBody String request) {
        Logger.info("[==== foget/password ====] request：" + request);
        // 转数据
        User bean = JSONObject.parseObject(request, User.class);
        // 查找用户
        User user = userAccountDao.findByMobileAndIdnumberAndEmail(bean.getMobile(), bean.getIdnumber(), bean.getEmail());
        if (user == null) {
            return response(1202, "该用户没有注册过", null);
        }
        user.setPassword(bean.getPassword());
        try {
            userAccountDao.save(user);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "密码存数据失败", null);
        }
        return response(1200, "成功", null);
    }

    /**
     * 乘机人管理
     */

    @RequestMapping(value = "/add/passenger", method = RequestMethod.POST)
    @ResponseBody
    public String add_passenger(@RequestBody String request) {
        Logger.info("[==== add/passenger ====] request：" + request);
        // 转数据
        Passenger bean = JSONObject.parseObject(request, Passenger.class);
        // 查找乘机人
        Passenger isExitsPassenger = passengerDao.findByUseridAndMobileAndIdnumber(bean.getUserid(), bean.getMobile(), bean.getIdnumber());
        if (isExitsPassenger != null) {
            return response(1202, "该用户已存在", null);
        }
        Passenger passenger = new Passenger();
        passenger.setUserid(bean.getUserid());
        passenger.setUsername(bean.getUsername());
        passenger.setEmail(bean.getEmail());
        passenger.setMobile(bean.getMobile());
        passenger.setGender(bean.getGender());
        passenger.setIdnumber(bean.getIdnumber());
        passenger.setCreatetime(new Date());
        passenger.setUpdatetime(new Date());
        try {
            passengerDao.save(passenger);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "乘机人存数据失败", null);
        }
        return response(1200, "成功", null);
    }

    @RequestMapping(value = "/edit/passenger", method = RequestMethod.POST)
    @ResponseBody
    public String edit_passenger(@RequestBody String request) {
        Logger.info("[==== edit/passenger ====] request：" + request);
        // 转数据
        Passenger bean = JSONObject.parseObject(request, Passenger.class);
        // 查找用户
        Passenger passenger = passengerDao.findByPassengerid(bean.getPassengerid());
        if (passenger == null) {
            return response(1202, "查库失败", null);
        }
        passenger.setUsername(bean.getUsername());
        passenger.setEmail(bean.getEmail());
        passenger.setMobile(bean.getMobile());
        passenger.setGender(bean.getGender());
        passenger.setIdnumber(bean.getIdnumber());
        passenger.setUpdatetime(new Date());
        try {
            passengerDao.save(passenger);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "乘机人存数据失败", null);
        }
        return response(1200, "成功", null);
    }

    @RequestMapping(value = "/search/passenger", method = RequestMethod.POST)
    @ResponseBody
    public String search_passenger(@RequestBody String request) {
        Logger.info("[==== search/passenger ====] request：" + request);
        // 转数据
        Passenger bean = JSONObject.parseObject(request, Passenger.class);
        // 查找用户
        List<Passenger> passengers = passengerDao.findAllByUserid(bean.getUserid());
        if (passengers == null) {
            return response(1205, "未有乘机人", null);
        }
        return response(1200, "成功", passengers);
    }

    @RequestMapping(value = "/delete/passenger", method = RequestMethod.POST)
    @ResponseBody
    public String delete_passenger(@RequestBody String request) {
        Logger.info("[==== delete/passenger ====] request：" + request);
        // 转数据
        Passenger bean = JSONObject.parseObject(request, Passenger.class);
        // 查找用户
        try {
            passengerDao.deleteById(bean.getPassengerid());
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "存数据删除失败", null);
        }
        return response(1200, "成功", null);
    }


    /**
     * 联系人管理
     */
    @RequestMapping(value = "/add/linkman", method = RequestMethod.POST)
    @ResponseBody
    public String add_linkman(@RequestBody String request) {
        Logger.info("[==== add/linkman ====] request：" + request);
        // 转数据
        LinkMan bean = JSONObject.parseObject(request, LinkMan.class);
        // 查找乘机人
        LinkMan isExitsLinkMan = linkManDao.findByUseridAndMobileAndAndEmail(bean.getUserid(), bean.getMobile(), bean.getEmail());
        if (isExitsLinkMan != null) {
            return response(1202, "该用户已存在", null);
        }
        LinkMan linkMan = new LinkMan();
        linkMan.setUserid(bean.getUserid());
        linkMan.setUsername(bean.getUsername());
        linkMan.setEmail(bean.getEmail());
        linkMan.setMobile(bean.getMobile());
        linkMan.setCreatetime(new Date());
        linkMan.setUpdatetime(new Date());
        try {
            linkManDao.save(linkMan);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "联系人存数据失败", null);
        }
        return response(1200, "成功", null);
    }

    @RequestMapping(value = "/edit/linkman", method = RequestMethod.POST)
    @ResponseBody
    public String edit_linkman(@RequestBody String request) {
        Logger.info("[==== edit/linkman ====] request：" + request);
        // 转数据
        LinkMan bean = JSONObject.parseObject(request, LinkMan.class);
        // 查找用户
        LinkMan linkMan = linkManDao.findByLinkmanid(bean.getLinkmanid());
        if (linkMan == null) {
            return response(1202, "查库失败", null);
        }
        linkMan.setUsername(bean.getUsername());
        linkMan.setEmail(bean.getEmail());
        linkMan.setMobile(bean.getMobile());
        linkMan.setUpdatetime(new Date());
        try {
            linkManDao.save(linkMan);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "联系人存数据失败", null);
        }
        return response(1200, "成功", null);
    }

    @RequestMapping(value = "/search/linkman", method = RequestMethod.POST)
    @ResponseBody
    public String search_linkman(@RequestBody String request) {
        Logger.info("[==== search/linkman ====] request：" + request);
        // 转数据
        LinkMan bean = JSONObject.parseObject(request, LinkMan.class);
        // 查找用户
        List<LinkMan> linkMans;
        try {
            linkMans = linkManDao.findAllByUserid(bean.getUserid());
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "查询存数据失败", null);
        }
        if (linkMans == null || linkMans.size() == 0) {
            return response(1205, "未有联系人", null);
        }
        return response(1200, "成功", linkMans);
    }

    @RequestMapping(value = "/delete/linkman", method = RequestMethod.POST)
    @ResponseBody
    public String delete_linkman(@RequestBody String request) {
        Logger.info("[==== delete/linkman ====] request：" + request);
        // 转数据
        LinkMan bean = JSONObject.parseObject(request, LinkMan.class);
        // 查找用户
        try {
            linkManDao.deleteById(bean.getLinkmanid());
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "存数据删除失败", null);
        }
        return response(1200, "成功", null);
    }

    /**
     * 系统公告
     */
    @RequestMapping(value = "/search/systemtip", method = RequestMethod.POST)
    @ResponseBody
    public String search_systemtip(@RequestBody String request) {
        Logger.info("[==== search/systemtip ====] request：" + request);
        // 查询所有数据
        Iterable<SystemTip> all;
        try {
            all = systemTipDao.findAll();
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "查数据失败", null);
        }
        if (all == null) {
            return response(1205, "未有系统公告.", null);
        }
        Iterator<SystemTip> iterator = all.iterator();
        if (iterator == null) {
            return response(1205, "未有系统公告..", null);
        }
        List<SystemTip> tips = new ArrayList<>();
        while (iterator.hasNext()) {
            SystemTip tip = iterator.next();
            tips.add(tip);
        }
        if (tips.size() == 0) {
            return response(1205, "未有系统公告...", null);
        }
        return response(1200, "成功", tips);
    }

    /**
     * 机票相关
     */
    @RequestMapping(value = "/search/flightplay", method = RequestMethod.POST)
    @ResponseBody
    public String search_flight_play(@RequestBody String request) {
        Logger.info("[==== search/flightplay ====] request：" + request);
        // 转数据
        FlightPlay bean = JSONObject.parseObject(request, FlightPlay.class);
        List<FlightPlay> plays = null;
        try {
            if (bean.getFlightnumberid() != null && bean.getFlightnumberid().length() > 0) {
                plays = flightPlayDao.findAllByCityAndEndcityAndDepartdateAndFlightnumberid(bean.getCity(), bean.getEndcity(), bean.getDepartdate(), bean.getFlightnumberid());
            } else {
                plays = flightPlayDao.findAllByCityAndEndcityAndDepartdate(bean.getCity(), bean.getEndcity(), bean.getDepartdate());
            }
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "查数据失败", null);
        }
        if (plays == null || plays.size() == 0) {
            return response(1205, "数据库内无数据.", null);
        }
        // 根据航班号，查询对应的航班信息
        List<Flight> flights = new ArrayList<>();
        // 查询对应的价格
        List<Double> prices = new ArrayList<>();
        try {
            for (FlightPlay play : plays) {
                Flight flight;
                // 选择舱位
                if (bean.getCabinname() == null) {
                    flight = flightDao.findByFlightnumberid(play.getFlightnumberid());
                } else {
                    flight = flightDao.findByFlightnumberidAndCabinname(play.getFlightnumberid(), bean.getCabinname());
                }
                if (flight != null) {
                    flights.add(flight);
                }
            }
            Iterable<Flight> iterable = flightDao.findAll();
            if (iterable != null) {
                Iterator<Flight> iterator = iterable.iterator();
                while (iterator.hasNext()) {
                    Flight next = iterator.next();
                    prices.add(next.getTicketprice());
                }
            }
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "查航线线数据失败", null);
        }
        if (flights.size() == 0) {
            return response(1205, "数据库内无数据..", null);
        }
        // 返回数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("prices", prices);
        jsonObject.put("flights", flights);
        jsonObject.put("flightplays", plays);
        return response(1200, "成功", jsonObject);
    }

    @RequestMapping(value = "/save/order", method = RequestMethod.POST)
    @ResponseBody
    public String save_order(@RequestBody String request) {
        Logger.info("[==== save/order ====] request：" + request);
        // 转数据
        List<UserOrder> orders = JSONArray.parseArray(request, UserOrder.class);
        // 保存
        try {
            for (UserOrder order : orders) {
                // 删除被变更的订单
                deleteChangeOrder(order);
                // 重新保存新订单
                order.setOrderstatus(0);
                order.setCreatetime(new Date());
                order.setUpdatetime(new Date());
                order.setBoardinggate(order.getFlightnumberid().substring(0, order.getFlightnumberid().length() - 1));
                if (order.getOrderid() != null && order.getOrderid().length() > 0) {
                    order.setChangorder(1);
                } else {
                    order.setChangorder(0);
                }
                order.setOrderid(UUID.randomUUID().toString().replace("-", ""));
                userOrderDao.save(order);
                // 行程汇总
                updateUserTripSummary(order);
            }
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "保存数据失败", null);
        }
        // 修改航班线票量
        String flightnumberid = orders.get(0).getFlightnumberid();
        try {
            Flight flight = flightDao.findByFlightnumberid(flightnumberid);
            flight.setTicketcount(flight.getTicketcount() - orders.size());
            flightDao.save(flight);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "修改数据失败", null);
        }
        return response(1200, "成功", null);
    }

    // 删除被变更的订单
    private void deleteChangeOrder(UserOrder order) {
        try {
            if (order.getOrderid() == null || order.getOrderid().length() == 0) {
                return;
            }
            UserOrder userOrder = userOrderDao.findByOrderid(order.getOrderid());
            userOrderDao.delete(userOrder);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
        }
    }

    // 行程汇总
    private void updateUserTripSummary(UserOrder order) {
        try {
            // 乘机人
            Passenger passenger = passengerDao.findByUseridAndPassengerid(order.getUserid(), order.getPassengerid());
            if (passenger != null) {
                // 该乘机人是否存在于表内
                UserTripSummary summary = userTripSummaryDao.findByUsernameAndIdnumber(passenger.getUsername(), passenger.getIdnumber());
                if (summary == null) {
                    summary = new UserTripSummary();
                }
                summary.setUserid(order.getUserid());
                summary.setUsername(passenger.getUsername());
                summary.setIdnumber(passenger.getIdnumber());
                // 票价
                summary.setTicketprice(summary.getTicketprice() + order.getTicketprice());
                // 飞行里程
                summary.setMileage(summary.getMileage() + order.getMileage());
                // 飞行次数
                summary.setMilenumber(summary.getMilenumber() + 1);
                // 飞行时长
                summary.setMiletime(converMiletime(summary.getMiletime(), order.getMiletime()));
                // 保存
                userTripSummaryDao.save(summary);
            }

        } catch (Exception e) {
            Logger.info("updateUserTripSummary exception：" + e.getMessage());
        }
    }

    @RequestMapping(value = "/modify/order", method = RequestMethod.POST)
    @ResponseBody
    public String modify_order(@RequestBody String request) {
        Logger.info("[==== modify/order ====] request：" + request);
        // 转数据
        UserOrder bean = JSONObject.parseObject(request, UserOrder.class);
        try {
            UserOrder order = userOrderDao.findByOrderid(bean.getOrderid());
            if (order == null) {
                return response(1201, "未搜到该订单", null);
            }
            order.setOrderstatus(1);
            order.setUpdatetime(new Date());
            // 保存
            userOrderDao.save(order);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "未搜到该订单.", null);
        }
        return response(1200, "成功", null);
    }

    @RequestMapping(value = "/delete/order", method = RequestMethod.POST)
    @ResponseBody
    public String delete_order(@RequestBody String request) {
        Logger.info("[==== delete/order ====] request：" + request);
        // 转数据
        UserOrder bean = JSONObject.parseObject(request, UserOrder.class);
        try {
            UserOrder order = userOrderDao.findByOrderid(bean.getOrderid());
            if (order == null) {
                return response(1201, "未搜到该订单", null);
            }
            userOrderDao.delete(order);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "未搜到该订单.", null);
        }
        return response(1200, "成功", null);
    }

    @RequestMapping(value = "/refound/order", method = RequestMethod.POST)
    @ResponseBody
    public String refound_order(@RequestBody String request) {
        Logger.info("[==== refound/order ====] request：" + request);
        // 转数据
        RefoundOrder refoundOrders = JSONObject.parseObject(request, RefoundOrder.class);
        try {
            if (refoundOrders == null || refoundOrders.getOrderid().size() == 0) {
                return response(1201, "上送数据为空", null);
            }
            for (String orderid : refoundOrders.getOrderid()) {
                UserOrder order = userOrderDao.findByOrderid(orderid);
                if (order == null) {
                    return response(1201, "未搜到该订单", null);
                }
                userOrderDao.delete(order);
            }
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "未搜到该订单.", null);
        }
        return response(1200, "成功", null);
    }

    @RequestMapping(value = "/valid/order", method = RequestMethod.POST)
    @ResponseBody
    public String valid_order(@RequestBody String request) {
        Logger.info("[==== valid/order ====] request：" + request);
        // 转数据
        UserOrder bean = JSONObject.parseObject(request, UserOrder.class);
        try {
            UserOrder order = userOrderDao.findByOrderid(bean.getOrderid());
            if (order == null) {
                return response(1201, "未搜到该订单信息", null);
            }
            Passenger passenger = passengerDao.findByUseridAndPassengerid(order.getUserid(), order.getPassengerid());
            if (passenger == null) {
                return response(1201, "请检查该票乘机人是否存在", null);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("username", passenger.getUsername());
            jsonObject.put("idnumber", passenger.getIdnumber());
            return response(1200, "成功", jsonObject);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
        }
        return response(1201, "未搜到该订单.", null);
    }


    /**
     * 航班动态
     */
    @RequestMapping(value = "/search/play", method = RequestMethod.POST)
    @ResponseBody
    public String search_play(@RequestBody String request) {
        Logger.info("[==== search/play ====] request：" + request);
        // 转数据
        FlightInfomation bean = JSONObject.parseObject(request, FlightInfomation.class);

        // 响应报文
        List<JSONObject> lists = new ArrayList<>();
        // 按航班号+日期查询
        if (bean.getFlightnumberid() != null && bean.getFlightnumberid().length() > 0) {
            try {
                FlightInfomation info = flightInfomationDao.findByFlightnumberidAndDepartdate(bean.getFlightnumberid(), bean.getDepartdate());
                if (info == null) {
                    return response(1205, "未搜到相应航班,请重新选择.", null);
                }
                // 航班计划
                List<FlightPlay> plays = flightPlayDao.findByFlightnumberidAndDepartdate(bean.getFlightnumberid(), convert2Date(bean.getDepartdate()));
                // 组装响应报文
                for (int i = 0; i < plays.size(); i++) {
                    FlightPlay play = plays.get(i);
                    Flight flight = flightDao.findByFlightnumberid(play.getFlightnumberid());
                    lists.add(responsePlay(flight, play, info));
                }
                return response(1200, "成功", lists);
            } catch (Exception e) {
                Logger.info("exception：" + e.getMessage());
            }
            return response(1205, "未搜到相应航班,请重新选择.", null);
        }
        // 按出发城市+到达城市+日期查询
        try {
            List<FlightInfomation> infos = flightInfomationDao.findAllByDepartdate(bean.getDepartdate());
            for (int i = 0; i < infos.size(); i++) {
                FlightInfomation infomation = infos.get(i);
                // 航班计划
                FlightPlay play = flightPlayDao.findAllByDepartdateAndCityAndEndcityAndFlightnumberid(convert2Date(bean.getDepartdate()), bean.getCity(), bean.getEndcity(), infomation.getFlightnumberid());
                if (play == null) {
                    continue;
                }
                Flight flight = flightDao.findByFlightnumberid(play.getFlightnumberid());
                lists.add(responsePlay(flight, play, infomation));
            }
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1205, "未搜到相应航班,请重新选择.", null);
        }
        if (lists.size() == 0) {
            return response(1205, "未搜到相应航班,请重新选择", null);
        }
        return response(1200, "成功", lists);
    }

    /**
     * 特价机票
     */
    @RequestMapping(value = "/search/specailticket", method = RequestMethod.POST)
    @ResponseBody
    public String search_specailticket(@RequestBody String request) {
        Logger.info("[==== search/specailticket ====] request：" + request);
        // 转数据
        SpecialTicket bean = JSONObject.parseObject(request, SpecialTicket.class);
        // 响应报文
        JSONObject jsonObject = new JSONObject();
        try {
            List<SpecialTicket> specialTickets;
            if (bean.getCount() != 0) {
                int id = specialTicketDao.findAll().iterator().next().getSpecialticketid();
                specialTickets = specialTicketDao.findBySpecialticketidLessThan(bean.getCount() + id - 1);
                // 会员专享
                List<UserMemberZone> zones = userMemberZoneDao.findByMemberzoneidLessThan(bean.getCount() + id - 1);
                jsonObject.put("zones", zones);
            } else {
                specialTickets = specialTicketDao.findAllByCityAndEndcity(bean.getCity(), bean.getEndcity());
            }
            if (specialTickets == null || specialTickets.size() == 0) {
                return response(1205, "未搜到响应数据", null);
            }
            jsonObject.put("specials", specialTickets);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1205, "查询数据库失败", null);
        }
        return response(1200, "成功", jsonObject);
    }

    /**
     * 行程
     */
    @RequestMapping(value = "/search/order", method = RequestMethod.POST)
    @ResponseBody
    public String search_order(@RequestBody String request) {
        Logger.info("[==== search/order ====] request：" + request);
        // 转数据
        UserOrder bean = JSONObject.parseObject(request, UserOrder.class);
        // 响应报文
        JSONObject jsonObject = new JSONObject();
        try {
            List<UserOrder> lists = userOrderDao.findAllByUseridAndOrderstatus(bean.getUserid(), bean.getOrderstatus());
            if (lists != null && lists.size() > 0) {
                jsonObject.put("orders", lists);
                // 乘机人
                List<Passenger> passengers = new ArrayList<>();
                for (int i = 0; i < lists.size(); i++) {
                    UserOrder order = lists.get(i);
                    Passenger passenger = passengerDao.findByUseridAndPassengerid(order.getUserid(), order.getPassengerid());
                    passengers.add(passenger);
                }
                jsonObject.put("passengers", passengers);
            }
            // 行程汇总查询
            if (bean.getUserid() != null && bean.getUserid().length() > 0) {
                UserTripSummary summary = userTripSummaryDao.findByUsernameAndIdnumber(bean.getUsername(), bean.getIdnumber());
                if (summary != null) {
                    JSONObject summaryJson = new JSONObject();
                    summaryJson.put("mileage", (int) summary.getMileage());
                    summaryJson.put("miletime", summary.getMiletime());
                    summaryJson.put("milenumber", summary.getMilenumber());
                    summaryJson.put("ticketprice", (int) summary.getTicketprice());
                    jsonObject.put("summary", summaryJson);
                }
            }
            String result = JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect);
            return response(1200, "成功", JSONObject.parseObject(result));
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
        }
        return response(1205, "未搜到相应数据", null);
    }

    /**
     * 行程
     */
    @RequestMapping(value = "/search/order/account", method = RequestMethod.POST)
    @ResponseBody
    public String search_order_account(@RequestBody String request) {
        Logger.info("[==== search/order/account ====] request：" + request);
        // 转数据
        OrderAccount bean = JSONObject.parseObject(request, OrderAccount.class);
        // 响应报文
        JSONObject jsonObject = new JSONObject();
        // 查询乘机人
        try {
            Passenger passenger = passengerDao.findByUseridAndPassengerid(bean.getUserid(), bean.getPassengerid());
            if (passenger != null) {
                jsonObject.put("username", passenger.getUsername());
                jsonObject.put("idnumber", passenger.getIdnumber());
            }
        } catch (Exception e) {
            Logger.info("userAccountDao exception：" + e.getMessage());
        }
        // 查询联系人
        try {
            LinkMan linkMan = linkManDao.findByUseridAndLinkmanid(bean.getUserid(), bean.getLinkmanid());
            if (linkMan != null) {
                jsonObject.put("mobile", linkMan.getMobile());
                jsonObject.put("passenger", linkMan.getUsername());
            }
        } catch (Exception e) {
            Logger.info("userAccountDao exception：" + e.getMessage());
        }
        if (jsonObject.size() == 0) {
            return response(1205, "未搜到响应数据", null);
        }
        return response(1200, "成功", jsonObject);
    }

    /**
     * 座位号
     */
    @RequestMapping(value = "/save/order/seats", method = RequestMethod.POST)
    @ResponseBody
    public String save_order_seats(@RequestBody String request) {
        Logger.info("[==== save/order/seats ====] request：" + request);
        // 转数据
        UserOrderSeats bean = JSONObject.parseObject(request, UserOrderSeats.class);
        try {
            UserOrderSeats orderSeats = userOrderSeatsDao.findByCityAndEndcityAndDepartdateAndFlightnumberid(bean.getCity(), bean.getEndcity(), bean.getDepartdate(), bean.getFlightnumberid());
            if (orderSeats == null) {
                orderSeats = new UserOrderSeats();
                orderSeats.setCity(bean.getCity());
                orderSeats.setEndcity(bean.getEndcity());
                orderSeats.setDepartdate(bean.getDepartdate());
                orderSeats.setFlightnumberid(bean.getFlightnumberid());
            }
            String seats = orderSeats.getSeatindexs();
            if (seats == null || seats.length() == 0) {
                seats = "";
            }
            orderSeats.setSeatindexs(seats + bean.getSeatindexs() + "#");
            userOrderSeatsDao.save(orderSeats);
            // 修改订单座位号
            UserOrder userOrder = userOrderDao.findByOrderid(bean.getOrderid());
            userOrder.setSeatnumber(bean.getSeat());
            userOrderDao.save(userOrder);
            return response(1200, "成功", null);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
        }
        return response(1205, "保存数据失败", null);
    }

    @RequestMapping(value = "/search/order/seats", method = RequestMethod.POST)
    @ResponseBody
    public String search_order_seats(@RequestBody String request) {
        Logger.info("[==== search/order/seats ====] request：" + request);
        // 转数据
        UserOrderSeats bean = JSONObject.parseObject(request, UserOrderSeats.class);
        try {
            UserOrderSeats orderSeats = userOrderSeatsDao.findByCityAndEndcityAndDepartdateAndFlightnumberid(bean.getCity(), bean.getEndcity(), bean.getDepartdate(), bean.getFlightnumberid());
            if (orderSeats == null) {
                return response(1205, "未有选择座位的", null);
            }
            String[] seats = orderSeats.getSeatindexs().split("#");
            return response(1200, "成功", seats);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
        }
        return response(1205, "未有选择座位的", null);
    }


    /**
     * 个人报销
     */
    @RequestMapping(value = "/add/person/expense", method = RequestMethod.POST)
    @ResponseBody
    public String add_person_expense(@RequestBody String request) {
        Logger.info("[==== add/person/expense ====] request：" + request);
        // 转数据
        PersonExpense bean = JSONObject.parseObject(request, PersonExpense.class);
        // 查找个人
        PersonExpense isExitsPerson = personExpenseDao.findByTitleAndDuty(bean.getTitle(), bean.getDuty());
        if (isExitsPerson != null) {
            return response(1202, "该报销已存在", null);
        }
        PersonExpense person = new PersonExpense();
        person.setTitle(bean.getTitle());
        person.setDuty(bean.getDuty());
        person.setUserid(bean.getUserid());
        person.setCreatetime(new Date());
        person.setUpdatetime(new Date());
        try {
            personExpenseDao.save(person);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "存报销数据失败", null);
        }
        return response(1200, "成功", null);
    }

    @RequestMapping(value = "/edit/person/expense", method = RequestMethod.POST)
    @ResponseBody
    public String edit_person_expense(@RequestBody String request) {
        Logger.info("[==== edit/person/expense ====] request：" + request);
        // 转数据
        PersonExpense bean = JSONObject.parseObject(request, PersonExpense.class);
        // 查找用户
        PersonExpense person = personExpenseDao.findByPersonexpenseid(bean.getPersonexpenseid());
        if (person == null) {
            return response(1202, "查库失败", null);
        }
        person.setTitle(bean.getTitle());
        person.setDuty(bean.getDuty());
        person.setUpdatetime(new Date());
        try {
            personExpenseDao.save(person);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "存报销数据失败", null);
        }
        return response(1200, "成功", null);
    }

    @RequestMapping(value = "/search/person/expense", method = RequestMethod.POST)
    @ResponseBody
    public String search_person_expense(@RequestBody String request) {
        Logger.info("[==== search/person/expense ====] request：" + request);
        // 转数据
        PersonExpense bean = JSONObject.parseObject(request, PersonExpense.class);
        // 查找用户
        List<PersonExpense> persons;
        try {
            persons = personExpenseDao.findAllByUserid(bean.getUserid());
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "查询存数据失败", null);
        }
        if (persons == null || persons.size() == 0) {
            return response(1205, "未有个人报销", null);
        }
        return response(1200, "成功", persons);
    }

    @RequestMapping(value = "/delete/person/expense", method = RequestMethod.POST)
    @ResponseBody
    public String delete_person_expense(@RequestBody String request) {
        Logger.info("[==== delete/person/expense ====] request：" + request);
        // 转数据
        PersonExpense bean = JSONObject.parseObject(request, PersonExpense.class);
        // 查找用户
        try {
            personExpenseDao.deleteById(bean.getPersonexpenseid());
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "存数据删除失败", null);
        }
        return response(1200, "成功", null);
    }

    /**
     * 企业报销
     */
    @RequestMapping(value = "/add/company/expense", method = RequestMethod.POST)
    @ResponseBody
    public String add_company_expense(@RequestBody String request) {
        Logger.info("[==== add/company/expense ====] request：" + request);
        // 转数据
        CompanyExpense bean = JSONObject.parseObject(request, CompanyExpense.class);
        // 查找个人
        CompanyExpense isExitsPerson = companyExpenseDao.findByTitleAndDuty(bean.getTitle(), bean.getDuty());
        if (isExitsPerson != null) {
            return response(1202, "该报销已存在", null);
        }
        CompanyExpense company = new CompanyExpense();
        company.setTitle(bean.getTitle());
        company.setDuty(bean.getDuty());
        company.setUserid(bean.getUserid());
        company.setCreatetime(new Date());
        company.setUpdatetime(new Date());
        // 可以为空
        company.setCompanymobile(bean.getCompanymobile());
        company.setCompanyaddress(bean.getCompanyaddress());
        company.setBankname(bean.getBankname());
        company.setBankaccount(bean.getBankaccount());
        try {
            companyExpenseDao.save(company);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "存报销数据失败", null);
        }
        return response(1200, "成功", null);
    }

    @RequestMapping(value = "/edit/company/expense", method = RequestMethod.POST)
    @ResponseBody
    public String edit_company_expense(@RequestBody String request) {
        Logger.info("[==== edit/company/expense ====] request：" + request);
        // 转数据
        CompanyExpense bean = JSONObject.parseObject(request, CompanyExpense.class);
        // 查找用户
        CompanyExpense company = companyExpenseDao.findByCompanyexpenseid(bean.getCompanyexpenseid());
        if (company == null) {
            return response(1202, "查库失败", null);
        }
        company.setTitle(bean.getTitle());
        company.setDuty(bean.getDuty());
        company.setUpdatetime(new Date());
        // 可以为空
        company.setCompanymobile(bean.getCompanymobile());
        company.setCompanyaddress(bean.getCompanyaddress());
        company.setBankname(bean.getBankname());
        company.setBankaccount(bean.getBankaccount());
        try {
            companyExpenseDao.save(company);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "存报销数据失败", null);
        }
        return response(1200, "成功", null);
    }

    @RequestMapping(value = "/search/company/expense", method = RequestMethod.POST)
    @ResponseBody
    public String search_company_expense(@RequestBody String request) {
        Logger.info("[==== search/company/expense ====] request：" + request);
        // 转数据
        CompanyExpense bean = JSONObject.parseObject(request, CompanyExpense.class);
        // 查找用户
        List<CompanyExpense> persons;
        try {
            persons = companyExpenseDao.findAllByUserid(bean.getUserid());
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "查询存数据失败", null);
        }
        if (persons == null || persons.size() == 0) {
            return response(1205, "未有企业报销", null);
        }
        return response(1200, "成功", persons);
    }

    @RequestMapping(value = "/delete/company/expense", method = RequestMethod.POST)
    @ResponseBody
    public String delete_company_expense(@RequestBody String request) {
        Logger.info("[==== delete/company/expense ====] request：" + request);
        // 转数据
        CompanyExpense bean = JSONObject.parseObject(request, CompanyExpense.class);
        // 查找用户
        try {
            companyExpenseDao.deleteById(bean.getCompanyexpenseid());
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
            return response(1201, "存数据删除失败", null);
        }
        return response(1200, "成功", null);
    }

    /**
     * 会员专享
     */
    @RequestMapping(value = "/search/memberzone", method = RequestMethod.POST)
    @ResponseBody
    public String search_memberzone(@RequestBody String request) {
        Logger.info("[==== search/memberzone ====] request：" + request);
        try {
            Iterable<UserMemberZone> iterable = userMemberZoneDao.findAll();
            if (iterable == null) {
                return response(1205, "查询数据库失败", null);
            }
            Iterator<UserMemberZone> iterator = iterable.iterator();
            if (iterator == null) {
                return response(1205, "查询数据库失败", null);
            }
            List<UserMemberZone> zones = new ArrayList<>();
            while (iterator.hasNext()) {
                UserMemberZone zone = iterator.next();
                zones.add(zone);
            }
            if (zones.size() == 0) {
                return response(1205, "查询数据库失败", null);
            }
            return response(1200, "成功", zones);
        } catch (Exception e) {
            Logger.info("exception：" + e.getMessage());
        }
        return response(1205, "查询数据库失败", null);
    }
}
